#include "mycoin.h"
#include <QDebug>
#include <QTimer>

MyCoin::MyCoin(QString btnImg){

    QPixmap pix;
    bool ret = pix.load(btnImg);
    if(!ret){
        qDebug() << QString("图片 %1 加载失败").arg(btnImg);
        return;
    }

    this->setFixedSize(pix.width(),pix.height());
    this->setStyleSheet("QPushButton{border:None;}");
    this->setIcon(pix);
    this->setIconSize(QSize(pix.width(),pix.height()));

    time1 = new QTimer(this); // 正面翻转到反面定时器
    time2 = new QTimer(this); // 反面翻转到正面定时器

    connect(time1,&QTimer::timeout,this,[=](){
        QPixmap pix;
        QString imgPath = QString(":/res/Coin000%1.png").arg(this->min++);
        pix.load(imgPath);
        this->setFixedSize(pix.width(),pix.height());
        this->setStyleSheet("QPushButton{border:None;}");
        this->setIconSize(QSize(pix.width(),pix.height()));
        this->setIcon(pix);
        if(this->min > this->max){
            this->min = 1;
            time1->stop();
            this->changing = false;
        }
    });

    connect(time2,&QTimer::timeout,this,[=](){
        QPixmap pix;
        QString imgPath = QString(":/res/Coin000%1.png").arg(this->max--);
        pix.load(imgPath);
        this->setFixedSize(pix.width(),pix.height());
        this->setStyleSheet("QPushButton{border:None;}");
        this->setIconSize(QSize(pix.width(),pix.height()));
        this->setIcon(pix);
        if(this->max < this->min){
            this->max = 8;
            time2->stop();
            this->changing = false;
        }
    });
}

void MyCoin::changeCoin(){
    // 正在翻转或者关卡完成了不进行翻转
    if(this->changing || this->done) return;
    this->changing = true;
    if(this->flag){
        // 正面翻转到反面
        this->flag = false;
        time1->start(30);
    }else {
        // 反面翻转到正面
        this->flag = true;
        time2->start(30);
    }
}
